package com.ruoyi.central.publisher.subscription.art.process.run.event;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ruoyi.central.domain.TopCentralArtProcessRun;
import com.ruoyi.central.domain.TopCentralProcessStepRun;
import com.ruoyi.central.publisher.event.ArtProcessRunEvent;
import com.ruoyi.central.service.ITopCentralProcessStepRunService;
import com.ruoyi.common.enums.common.TaskStatusEnum;
import com.ruoyi.common.exception.base.service.ServiceException;
import com.ruoyi.common.utils.CollectionUtils;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.List;

/**
 * @Classname ArtProcessRunEvent
 * @Author: sunluquan
 * @Date: 2022/5/24 18:53
 * @Description TODO
 * 执行工艺对象 事件发布 订阅对象
 */
@Component
@Order(1)
public class ArtProcessRunEventSubscription {

    @Autowired
    private ITopCentralProcessStepRunService processStepRunService;

    @EventListener(value = ArtProcessRunEvent.class,condition = "#event.getSignEnum().name()=='DELETE'")
    public void deleteEvent(ArtProcessRunEvent event){

        List<Integer> artProcessRunIds = CollectionUtils.mapToList(event.getSources(), TopCentralArtProcessRun::getId);

        LambdaQueryWrapper<TopCentralProcessStepRun> queryWrapper = processStepRunService.customLambdaQuery();

        queryWrapper.select(TopCentralProcessStepRun::getId,TopCentralProcessStepRun::getName);
        queryWrapper.eq(TopCentralProcessStepRun::getTaskStatus, TaskStatusEnum.EXECUTING.getValue());
        if(artProcessRunIds.size()==1){
            queryWrapper.eq(TopCentralProcessStepRun::getId,CollectionUtils.getFirst(artProcessRunIds));
        }else{
            queryWrapper.in(TopCentralProcessStepRun::getId,artProcessRunIds);
        }
        List<TopCentralProcessStepRun> processStepRuns = processStepRunService.selectSimpleList(queryWrapper);

        if(StringUtils.isNotEmpty(processStepRuns)){
            List<String> canNotArtProcessNames = CollectionUtils.mapToList(processStepRuns, TopCentralProcessStepRun::getName);
            throw new ServiceException("工艺{}状态为 ：{} ，不能进行删除！", Arrays.toString(canNotArtProcessNames.toArray()),TaskStatusEnum.EXECUTING.getDescription());
        }

    }
}
